//
//  CheckTool.swift
//  NetCheck
//
//  Created by 郑东喜 on 2016/11/25.
//  Copyright © 2016年 郑东喜. All rights reserved.
//

import UIKit

class CheckTool: NSObject {
    static let shared = CheckTool()
    //检测网络工具
    var reachability: Reachability?
    
    var hostNameLabel = "baidu.com"
    
    //外部闭包变量
    var comfun:((_ _data:String)->Void)?

    
    func check(comfun:((_ _data:String)->Void)?) -> Void {
        
        self.comfun = comfun
        
        // After 5 seconds, stop and re-start reachability, this time using a hostname
        let dispatchTime = DispatchTime.now() + DispatchTimeInterval.seconds(5)
        DispatchQueue.main.asyncAfter(deadline: dispatchTime) {
            self.stopNotifier()
            self.setupReachability("www.baidu.com", useClosures: true)
            self.startNotifier()
            
            let dispatchTime = DispatchTime.now() + DispatchTimeInterval.seconds(5)
            DispatchQueue.main.asyncAfter(deadline: dispatchTime) {
                self.stopNotifier()
                self.setupReachability("invalidhost", useClosures: true)
                self.startNotifier()
            }
            
        }

    }
    
    func setupReachability(_ hostName: String?, useClosures: Bool) {
        hostNameLabel = hostName != nil ? hostName! : "No host name"
        
        print("--- set up with host name: \("baidu.com")")
        
        let reachability = hostName == nil ? Reachability() : Reachability(hostname: hostName!)
        self.reachability = reachability
        
        if useClosures {
            reachability?.whenReachable = { reachability in
                DispatchQueue.main.async {
                    self.updateLabelColourWhenNotReachable(reachability)
                }
            }
            reachability?.whenUnreachable = { reachability in
                DispatchQueue.main.async {
                    self.updateLabelColourWhenNotReachable(reachability)
                }
            }
        } else {
            NotificationCenter.default.addObserver(self, selector: #selector(CheckTool.reachabilityChanged(_:)), name: ReachabilityChangedNotification, object: reachability)
        }
    }
    
    
    func updateLabelColourWhenNotReachable(_ reachability: Reachability) {
        print("\(reachability.description) - \(reachability.currentReachabilityString)")
        
        //闭包传值
        self.comfun!(reachability.currentReachabilityString)
        

        print(reachability.currentReachabilityString)
    }
    
    func reachabilityChanged(_ note: Notification) {
        let reachability = note.object as! Reachability
        
        if reachability.isReachable {
            updateLabelColourWhenReachable(reachability)
        } else {
            updateLabelColourWhenNotReachable(reachability)
        }
    }
    
    func updateLabelColourWhenReachable(_ reachability: Reachability) {
        print("\(reachability.description) - \(reachability.currentReachabilityString)")
        
            self.comfun!(reachability.currentReachabilityString)
        
        if reachability.isReachableViaWiFi {
            self.comfun!(reachability.currentReachabilityString)
            print("yes  ssss ")
        } else {

            print("nononononon")
        }
        
    }
    
    //开始通知
    func startNotifier() {
        print("--- start notifier")
        do {
            try reachability?.startNotifier()
        } catch {

            
            print("Unable to start\nnotifier")
            return
        }
    }
    
    //停止通知
    func stopNotifier() {
        print("--- stop notifier")
        reachability?.stopNotifier()
        NotificationCenter.default.removeObserver(self, name: ReachabilityChangedNotification, object: nil)
        reachability = nil
    }
    
    //移除通知
    deinit {
        stopNotifier()
    }
    
}
